package cn.iocoder.yudao.module.system.job;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;

import cn.iocoder.yudao.module.system.controller.admin.portal.vo.OrgApiResponseVO;
import cn.iocoder.yudao.module.system.controller.admin.portal.vo.PortalDeptSaveReqVO;
import cn.iocoder.yudao.module.system.dal.dataobject.portal.PortalDeptDO;
import cn.iocoder.yudao.module.system.dal.dataobject.portal.PortalUserDO;
import cn.iocoder.yudao.module.system.service.portal.PortalDeptService;
import cn.iocoder.yudao.module.system.service.portal.PortalUserService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * @Description: 用户、组织机构同步
 * @Author: meiwanli
 * @Date: 2025-10-09 14:48
 */
@Component
@Slf4j
public class OrganizationalTask {

    @Resource
    private PortalUserService portalUserService;
    @Resource
    private PortalDeptService portalDeptService;

    // 每天0点执行
    @Scheduled(cron = "0 0 0 * * ?")
    @Transactional(rollbackFor = Exception.class)
    public void syncUserAndOrganization() throws JsonProcessingException {
        // 1、调用http://192.168.0.12:8188/nvwa-path/anon/getToken?appId=1012 ,从接口返回值中“{"msg":"操作成功","code":0,"token":"4e595c47515052465e5f525959514d"}” 取出token
        String getTokenUrl = "http://192.168.0.12:8188/nvwa-path/anon/getToken?appId=1012";
        String token = "";
        HttpResponse response = HttpRequest.get(getTokenUrl)
                .timeout(5000)
                .execute();
        String getTokenResponseJson = response.body();
        log.info("获取token成功：" + getTokenResponseJson);

        JSONObject getTokenJson = JSONUtil.parseObj(getTokenResponseJson);

        // 先判断接口是否成功（按你的返回值实例，code=0表示成功）
        if (getTokenJson.getInt("code") == 0) {
            token = getTokenJson.getStr("token");
            String getOrganizationalUrl = "http://192.168.0.12:8188/nvwa-path/anon/getUserOrgRole?token=" + token;
            HttpResponse response1 = HttpRequest.get(getOrganizationalUrl)
                    .timeout(5000)
                    .execute();
            String getOrganizationalResponseJson = response1.body();
            log.info("获取组织架构成功：" + getOrganizationalResponseJson);
            JSONObject getOrganizationalJson = JSONUtil.parseObj(getOrganizationalResponseJson);
            if (getOrganizationalJson.getInt("code") == 0) {
                log.info("获取组织架构成功：" + getOrganizationalJson.getStr("msg"));
                // 2. 初始化Jackson的ObjectMapper
                ObjectMapper objectMapper = new ObjectMapper();
                // 3. 将JSON字符串转换为ApiResponse对象（自动映射userData和orgData为List）
                OrgApiResponseVO apiResponse = objectMapper.readValue(getOrganizationalResponseJson, OrgApiResponseVO.class);

                // 4. 提取转换后的List<UserInfo>和List<OrgInfo>
                List<PortalUserDO> userList = apiResponse.getUserDataList();
                List<PortalDeptSaveReqVO> orgList = apiResponse.getOrgDataList();

                portalDeptService.deleteAll();
                portalUserService.deleteAll();

                // 批量插入
                portalDeptService.batchCreateDept(orgList);
                portalUserService.batchCreateUser(userList);
            } else {
                // 获取失败
                log.error("获取组织架构失败：" + getOrganizationalJson.getStr("msg"));
            }

        } else {
            // 接口返回错误（如code≠0）
            String errorMsg = getTokenJson.getStr("msg");
            log.error("获取token失败：" + errorMsg);
        }
    }


}
